<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class MY_Controller extends CI_Controller {

  public $error = array();
  public $data = array();
  public $template = 'template.html';

  public function __construct() {
    parent::__construct();
    @define('BASE_URL', $this->config->item('base_url'));
    @define('FILE_PATH', BASE_URL . "sources/");
    $this->data['controller'] = $this->router->fetch_class();
    $this->data['method'] = $this->router->fetch_method();
    $this->data['current_user'] = $this->session->userdata('current_user');
    /* if ($this->data['current_user'] == false) {
      if ($this->data['method'] != 'login') {
        $this->session->set_flashdata('error', 'You must login first.');
        redirect(base_url('users/login'));
      }
    } */
    // if (!empty($this->data['current_user'])) {
    //   $this->session->userdata('current_user');
    //   $this->data['ID_SBU'] = $this->data['current_user']->ID_SBU;
    // }
    // $this->smarty->assign('BASE_URL', BASE_URL);
    // $this->smarty->assign('IMG_PATH', BASE_URL . "sources/uploads/");
    // $this->smarty->assign('FILE_PATH', BASE_URL . "sources/");
    // $this->smarty->assign('JS_PATH_MODULE', BASE_URL . "js/module/");

    // $this->smarty->append("FILE_CSS", FILE_PATH . "css/bootstrap.css");
    // $this->smarty->append("FILE_CSS", FILE_PATH . "css/bootstrap-responsive.min.css");
    // $this->smarty->append("FILE_CSS", FILE_PATH . "css/custom.css");
    // $this->smarty->append("FILE_JS", $this->all_js->addJS("variable"));
    // $this->smarty->append("FILE_JS", $this->all_js->addJS("jquery"));
    // $this->smarty->append("FILE_JS", $this->all_js->addJS("bootstrap"));
    // $this->smarty->append("FILE_JS", $this->all_js->addJS("notification"));
    // $this->smarty->append("FILE_JS", $this->all_js->addJS("jquery.typing"));
    // if ($this->data['controller'] . "/" . $this->data['method'] != "users/login") {
    //   $this->smarty->append("FILE_CSS", FILE_PATH . "css/bootstrap-timepicker.min.css");
    //   $this->smarty->append("FILE_CSS", FILE_PATH . "datepicker/base/jquery.ui.all.css");
    //   $this->smarty->append("FILE_CSS", FILE_PATH . "tree_menu/style.css");
    //   $this->smarty->append("FILE_JS", $this->all_js->addJS("bootstrap-modal"));
    //   $this->smarty->append("FILE_JS", $this->all_js->addJS("ajaxupload"));
    //   $this->smarty->append("FILE_JS", $this->all_js->addJS("validation"));
    //   $this->smarty->append("FILE_JS", $this->all_js->addJS("numeric"));

    //   $this->smarty->append("FILE_JS", $this->all_js->addJS("datepicker"));
    //   $this->smarty->append("FILE_JS", $this->all_js->addJS("timepicker"));
    //   $this->smarty->append("FILE_JS", $this->all_js->addJS("treemenu"));
    //   $this->smarty->append("FILE_JS", $this->all_js->addJS("template"));
    //   $this->smarty->assign("header", $this->load->view("shared/header", null, true));
    //   $this->smarty->assign("tree_menu", $this->load->view("shared/tree_menu", null, true));
    //   $this->smarty->assign("overlay", $this->load->view("shared/overlay", null, true));
    //   $this->smarty->assign("template_confirmation_box", $this->load->view("shared/template_confirmation_box", null, true));
    // } else {
    //   $this->template = "auth_template.html";
    //   $this->smarty->assign("header_auth", $this->load->view("shared/header_auth", null, true));
    // }

    // $this->smarty->assign("TITLE", "Human Resource Management");
    // $this->smarty->assign("notification_error", $this->session->flashdata('error'));
    // $this->smarty->assign("notification_success", $this->session->flashdata('success'));
    
  }

  // protected function render($data = null, $view = null, $partial = null) {
  //   if (isset($data['breadcrumb']) && $data != null) {
  //     $data['breadcrumb'] = '<ul class="breadcrumb">' . $data['breadcrumb'] . '</ul>';
  //   }
  //   $data['CONTROLLER']=$this->data['controller'];
  //   $data['METHOD']=$this->data['method'];
  //   if ($partial != null) {
  //     foreach ($partial as $key => $part) {
  //       $data[$key] = $this->load->view($part, $data, true);
  //     }
  //   }
  //   if ($this->input->is_ajax_request())$this->template = 'ajax_template.html';
  //   $url = $this->data['controller'] . '/' . $this->data['method'];
  //   if ($view != null) {
  //     $views = explode('/', $view);
  //     if (sizeof($views) == 2) {
  //       $url = $views[0] . '/' . $views[1];
  //     } else {
  //       $url = $this->data['controller'] . '/' . $view;
  //     }
  //   }
  //   $this->smarty->assign("controller", $data['CONTROLLER']);
  //   $this->smarty->assign("method", $data['METHOD']);
  //   $this->smarty->assign("view", $this->load->view($url, $data, true));
  //   $this->smarty->view($this->template, $data);
  //   $this->smarty->clearAllCache();
  // }
  function render ($tpl_view, $body_view = null, $data = null) 
   {
      if ( ! is_null( $body_view ) ) 
      {
       if ( file_exists( APPPATH.'views/'.$tpl_view.'/'.$body_view ) ) 
       {
          $body_view_path = $tpl_view.'/'.$body_view;
       }
       else if ( file_exists( APPPATH.'views/'.$tpl_view.'/'.$body_view.'.php' ) ) 
       {
          $body_view_path = $tpl_view.'/'.$body_view.'.php';
       }
       else if ( file_exists( APPPATH.'views/'.$body_view ) ) 
       {
          $body_view_path = $body_view;
       }
       else if ( file_exists( APPPATH.'views/'.$body_view.'.php' ) ) 
       {
          $body_view_path = $body_view.'.php';
       }
       else
       {
          show_error('Unable to load the requested file: ' . $tpl_name.'/'.$view_name.'.php');
       }
         
       $body = $this->load->view($body_view_path, $data, TRUE);
         
       if ( is_null($data) ) 
       {
          $data = array('body' => $body);
       }
       else if ( is_array($data) )
       {
          $data['body'] = $body;
       }
       else if ( is_object($data) )
       {
          $data->body = $body;
       }
      }
        
      $this->load->view('template/'.$tpl_view, $data);
   }

  function paging($param = array()) {
    $config['base_url'] = $param['base_url'];
    $config['total_rows'] = $param['total_rows'];
    $config['per_page'] = $param['per_page'];
    $config['num_links'] = $param['num_links'];
    $config['uri_segment'] = $param['uri_segment'];
    $config['full_tag_open'] = '<div class="pagination pagination-right"><ul>';
    $config['full_tag_close'] = '</ul></div>';
    $config['first_link'] = '&nbsp;First&nbsp;';
    $config['last_link'] = '&nbsp;Last&nbsp;';
    $config['next_link'] = '&nbsp;Next&nbsp;';
    $config['prev_link'] = '&nbsp;Previous&nbsp;';
    $config['cur_tag_open'] = '<li><a style="color:gray">';
    $config['cur_tag_close'] = '</a></li>';
    $config['num_tag_open'] = '<li>';
    $config['num_tag_close'] = '</li>';
    $this->pagination->initialize($config);
    return $this->pagination->create_links();
  }

  function call_sprocedure($proc_name, $params = array(), $type = "proc") {
    $parameter = "";
    for ($x = 0; $x < sizeof($params); $x++) {
      $parameter.="?";
      (($x + 1) < sizeof($params)) ? $parameter.="," : "";
    }
    if ($type == "proc") {
      $result = $this->db->query("call $proc_name($parameter)", $params);
    } else {
      $result = $this->db->query("select " . $proc_name . "(" . $parameter . ") as result_function", $params);
    }
    $error_number = $this->db->_error_number();
    $error_message = $this->db->_error_message();
    $trans_status = $this->db->trans_status();
    if ($trans_status === FALSE) {
      if ($error_number != 0) {
        $error = array(
            'error_number' => $error_number,
            'error_message' => "Some transaction has been rollback.". $error_message,
            'status' => $trans_status
        );
        $this->error_message($error);
      }
      $row = array();
    } else {
      $row = $result->result();
      $result->next_result();
      $result->free_result();
    }
    return $row;
  }
  
  function call_sp($proc_name, $params = array(), $type = "proc") {
    $parameter = "";
    for ($x = 0; $x < sizeof($params); $x++) {
      $parameter.="?";
      (($x + 1) < sizeof($params)) ? $parameter.="," : "";
    }
    $this->db->trans_start();
    if ($type == "proc") {
      $result = $this->db->query("call $proc_name($parameter)", $params);
    } else {
      $result = $this->db->query("select " . $proc_name . "(" . $parameter . ") as result_function", $params);
    }
    $error_number = $this->db->_error_number();
    $error_message = $this->db->_error_message();
    $trans_status = $this->db->trans_status();
    $this->db->trans_complete();

    if ($trans_status === FALSE) {
      $this->db->trans_rollback();
      if ($error_number != 0) {
        $error = array(
            'error_number' => $error_number,
            'error_message' => "Some transaction has been rollback.". $error_message,
            'status' => $trans_status
        );
        $this->error_message($error);
      }
      $this->db->trans_rollback();
      $row = array();
    } else {
      $row = $result->result();
      $result->next_result();
      $result->free_result();
    }
    return $row;
  }

  function upload_file($location, $field) {
    $config['upload_path'] = $location;
    $config['allowed_types'] = '*';
    $config['remove_spaces'] = TRUE;
    $this->load->library('upload', $config);
    $this->upload->display_errors('', '');
    if (!$this->upload->do_upload($field)) {
      $error = $this->upload->display_errors();
    } else {
      $data = $this->upload->data();
    }
    return $data;
  }

  function error_message($error = array()) {
    $message = "";
    switch (intval($error['error_number'])) {
      case 1318 : $message = "Incorrect number of arguments for PROCEDURE, please call your administrator to fix it.";
        break;
      case 1062 : $message = "Duplicate entry for Primary Key, please call your administrator to fix it.";
        break;
      case 1305 : $message = "PROCEDURE does not exist, please call your administrator to fix it.";
        break;
      case 1452 : $message = "Cannot add or update a child row: a foreign key constraint fails, please call your administrator to fix it.";
        break;
      case 1242 : $message ="Sub query return more than one row, please call your administrator to fix it.";
        break;
      case 10060 : show_404(); //CONNECTION TIME OUT
        break;
    }
    $this->error = array(
      'message' => $message
    );
  }

  public function return_result($presult = 0, $predirect = "index", $pmessage = "Item") {
    if ($presult > 0) {
      $this->data['type_message'] = "error";
      $this->data['message'] = $result[0]->err_msg;
      $this->session->set_flashdata('error', $result[0]->err_msg);
      redirect($predirect);
    } else {
      $this->data['type_message'] = "success";
      $this->data['message'] = $pmessage . " has been added.";
      $this->session->set_flashdata('success', $pmessage . " has been added.");
      redirect($predirect);
    }
  }
	
  public function debug($data=array()) {
    echo "<pre>";
    print_r($data); 
    echo"</pre>";
  }
}